{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Contiguous Subarray with Maximum Sum\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/Meb_tn2_9tsyFpvf_PaVLA)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "You are given an array of integers. Find the maximum sum of all possible contiguous subarrays of the array.\n",
    "\n",
    "Your solution should run in linear time."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example\n",
    "\n",
    "```python3\n",
    "[34, -50, 42, 14, -5, 86]\n",
    "```\n",
    "\n",
    "Given this input array, the output should be `137`. The contiguous subarray with the largest sum is `[42, 14, -5, 86]`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def max_subarray_sum(array):\n",
    "    this_sum = max_sum = 0\n",
    "    for k in array:\n",
    "        this_sum += k\n",
    "        if this_sum > max_sum:\n",
    "            max_sum = this_sum\n",
    "        elif this_sum < 0:\n",
    "            this_sum = 0\n",
    "    return max_sum"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "137\n"
     ]
    }
   ],
   "source": [
    "print(max_subarray_sum([34, -50, 42, 14, -5, 86]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Notes\n",
    "\n",
    "1. The first element of the maximum sub-array won't be negative.\n",
    "\n",
    "    If `sub_array[0]` is negative, then any sum start from `sub_array[0]` must less than that from `sub_array[1]`.\n",
    "\n",
    "2. Any sub-array that sum to negative won't be the prefix of the maximum sub-array."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
